<?php

namespace App\library\services;

use App\Models\WxUser as WxUserModel;
use App\Models\Order as OrderModel;

class PayService extends BaseServices
{
    /**余额支付
     * auth::william
     * @param array $params
     * @return string
     */
    public static function balancePay($params = [])
    {
        if (empty($params['pay_price'])) {
            return self::fail('参数错误');
        }
        if (empty($params['order_no'])) {
            return self::fail('参数错误');
        }
        if (!is_numeric($params['user_id'])) {
            return self::fail('参数错误');
        }
        $userBalance = WxUserModel::where('id', $params['user_id'])->value('money');
        $price = $params['pay_price'];
        //减法计算
        $newUserBalance = bcsub($userBalance, $price);
        if ($newUserBalance >= 0) {
            try {
                self::beginTrans();
                //修改余额
                $userRes = WxUserModel::where('id', $params['user_id'])->update(['money' => $newUserBalance]);
                //修改订单状态
                $orderRes = OrderModel::where('order_no', $params['order_no'])->update(['status' => 1,'pay_type'=>3]);
                //添加消费记录
                $userConsume = UserConsumeService::create($params['user_id'],$params['order_no']);
                if ($userConsume['code'] != 200) {
                    return self::fail($userBalance['message']);
                }
                self::commitTrans();
                return self::success('支付成功', $orderRes);
            } catch (\Exception $e) {
                self::rollbackTrans();
                return '支付失败';
            }
        } else {
            return '余额不足';
        }
    }
}
